package runtime

import (
	"encoding/json"
	"gitee.com/pearl-zz/go-manage-system-core/storage"
	"github.com/chanxuehong/wechat/oauth2"
	"time"
)

const (
	intervalTenant = "/"
)

type Cache struct {
	prefix          string
	store           storage.AdapterCache
	wxTokenStoreKey string
}

// NewCache 实例化
func NewCache(prefix string, store storage.AdapterCache, wxTokenStoreKey string) storage.AdapterCache {
	if wxTokenStoreKey == "" {
		wxTokenStoreKey = "wx_token_store_key"
	}

	return &Cache{
		prefix:          prefix,
		store:           store,
		wxTokenStoreKey: wxTokenStoreKey,
	}
}

// SetPrefix 设置前缀
func (c *Cache) SetPrefix(prefix string) {
	c.prefix = prefix
}
func (c Cache) Connect() error {
	return nil
}

func (c *Cache) String() string {
	if c.store == nil {
		return ""
	}
	return c.store.String()
}

func (c *Cache) Get(key string) (string, error) {
	return c.store.Get(c.prefix + intervalTenant + key)
}

func (c *Cache) Set(key string, val interface{}, expire int) error {
	return c.store.Set(c.prefix+intervalTenant+key, val, expire)
}

func (c *Cache) Del(key string) error {
	return c.store.Del(c.prefix + intervalTenant + key)
}

func (c *Cache) HashGet(hk, key string) (string, error) {
	return c.store.HashGet(hk, c.prefix+intervalTenant+key)
}

func (c *Cache) HashDel(hk, key string) error {
	return c.store.HashDel(hk, c.prefix+intervalTenant+key)
}

func (c *Cache) Increase(key string) error {
	return c.store.Increase(c.prefix + intervalTenant + key)
}

func (c *Cache) Decrease(key string) error {
	return c.store.Decrease(c.prefix + intervalTenant + key)
}

func (c *Cache) Expire(key string, dur time.Duration) error {
	return c.store.Expire(c.prefix+intervalTenant+key, dur)
}

// Token 获取微信oauth2 token
func (c *Cache) Token() (token *oauth2.Token, err error) {
	var str string
	str, err = c.store.Get(c.prefix + intervalTenant + c.wxTokenStoreKey)
	if err != nil {
		return
	}

	err = json.Unmarshal([]byte(str), token)
	return
}

// PutToken 设置微信oauth2 token
func (c *Cache) PutToken(token *oauth2.Token) error {
	data, err := json.Marshal(token)
	if err != nil {
		return err
	}
	return c.store.Set(c.prefix+intervalTenant+c.wxTokenStoreKey, string(data), int(token.ExpiresIn)-200)
}
